<?php

namespace Trawind\Workflows;

use Illuminate\Support\Facades\Request;
use Trawind\Helpers\HttpClientHelper;
use Trawind\Workflows\Models\Microservices;

trait ServiceConnect
{
    protected $domain = '';
    protected $serviceConnectionName = 'account';
    protected $prefix = '/workflow-execute';

    /**
     * Undocumented function
     *
     * @return void
     */
    protected function requestHeaders(): array
    {
        return [
            'Accept' => 'application/json',
            'Authorization' => Request::header('Authorization', null),
            // 'MS-Request-ServiceName' => null
        ];
    }

    /**
     * make Domain
     */
    protected function makeDomain(): string
    {
        $microservice = Microservices::where(['name' => $this->serviceConnectionName])->first();
        $domain = $microservice->domain;
        $env = config('app.env');
        $port = Request::getPort();
        $hostname = Request::getHost();
        $tenantId = explode('.', $hostname)[0];
        $tenantStr = $tenantId . '.';
        // if (is_numeric($tenantId)) $tenantStr = $tenantId . '.';
        // else $tenantStr = '';
        return "{$tenantStr}" . "{$env}" . ".{$domain}" . ($port ? ':' . $port : '') . $this->prefix;

        // $appRootUrl = env('APP_ROOT_URL');
        // $appEnv = config('app.env');
        // $port = Request::getPort();
        // // $tenantId = tenant('tenant_id');
        // $hostname = Request::getHost();
        // $tenantId = explode('.', $hostname)[0];
        // $tenantStr = $tenantId . '.';
        // return "{$tenantStr}{$appEnv}." . $this->serviceConnectionName . ".{$appRootUrl}" . ($port ? ':' . $port : '') .  $this->prefix;

    }

    /**
     * request
     *
     * @param string $path
     * @param array $requestBody
     * @param string $query
     * @return array
     */
    protected function request(string $path, array $requestBody = [], $query = '', $method = 'GET', ?array $header = null): array
    {
        $headers = $this->requestHeaders();
        if ($header) {
            $headers = array_merge($headers, $header);
        }
        $options = [
            'headers' => $headers,
            'json' => $requestBody
        ];
        $uri = $this->domain . $path . $query;

        $response = HttpClientHelper::factory()->client()->request($method, $uri, $options);
        if ($response->getStatusCode() == 200) {
            return json_decode($response->getBody(), true);
        } else {
            throw new \Exception($response->getBody());
        }
    }
}
